<?php

namespace App\Supports\Auth\Wechat;

use App\Models\User;
use Illuminate\Validation\ValidationException;

class WechatBinder extends WechatAuth
{
	protected function bindAccount(User $user)
	{
		if ($user->isWeixinBound()) {
			throw ValidationException::withMessages(['err' => '微信已被其它账号绑定']);
		}
		
		$this->httpValidate();
		
		$data = $this->authData;
		
		$user->update([
			'name' => $data->getNickname() . ' - ' . $user->id,
			'avatar' => $user->avatar ?? $data->getRaw()['headimgurl'],
			'wx_openid' => $this->openid,
			'wx_unionid' => $this->unionid,
			'wx_nickname' => $data->getNickname(),
			'wx_headimgurl' => $data->getRaw()['headimgurl'],
			'wx_sex' => $data->getRaw()['sex'],
			'wx_country' => $data->getRaw()['country'],
			'wx_province' => $data->getRaw()['province'],
			'wx_city' => $data->getRaw()['city'],
		]);
		
		return $user;
	}
	
	public function bind(User $user)
	{
		return $this->bindAccount($user);
	}
	
	protected function dismissAccount(User $user)
	{
		$user->update([
			'wm_openid' => null,
			'wm_session_key' => null,
			'wx_openid' => null,
			'wx_unionid' => null,
			'wx_nickname' => null,
			'wx_headimgurl' => null,
			'wx_sex' => null,
			'wx_country' => null,
			'wx_province' => null,
			'wx_city' => null,
			'wx_qrcode' => null,
		]);
	}
	
	public function dismiss(User $user)
	{
		$this->dismissAccount($user);
	}
}
